package com.i2863.watchdog.util;

import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xuweiwei
 * @date 2017/12/6
 */
public class HttpUtil {

    public static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded");
    public static final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();

    public static ResponseInfo get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)

                .build();

        Response response = client.newCall(request).execute();
        int code = response.code();
        String content = response.body().string();
        return new ResponseInfo(code, content);
    }


    public static ResponseInfo post(String url, Map<String, Object> param) throws IOException {
        StringBuilder result = new StringBuilder();
        Iterator<Map.Entry<String, Object>> iter = param.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Object> entry = iter.next();
            if (result.length() > 0) {
                result.append("&");
            }
            result.append(entry.getKey()).append("=").append(entry.getValue());
        }
        RequestBody body = RequestBody.create(FORM, result.toString());
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        int code = response.code();
        String content = response.body().string();
        return new ResponseInfo(code, content);
    }


    public static void main(String[] args) throws IOException {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("name", "张三");
        param.put("sex", "男");
        post("http://www.baidu.com", param);
    }
}
